<template>
    <div>
        <div class="monitor-container" 
             ref="container"
             @mousedown="startDrag"
             @dblclick="resetZoom">
            <div class="zoom-wrapper" :style="zoomTransform">
                <div class="background-layer" :style="backgroundStyle"></div>
                
                <template v-if="currentWorkEqList.length > 0">
                    <a-popover :title="eq.deviceName" trigger="hover" v-for="(eq,i) in currentWorkEqList" :key="i">
                        <template slot="content" v-if="eq.deviceType===defaultSettings.常量.设备类型_温湿度">
                            <a-row>
                                <img src="../img/wendu.png" style="width:20px;" />
                                <span style="font-weight: 500;">{{eq.deviceTemperature}}°C</span>
                            
                                <img src="../img/shidu.png" style="width:20px;" />
                                <span style="font-weight: 500;">{{eq.deviceHumidity}}%</span>
                                <img v-if="eq.alarmState===defaultSettings.常量.是" src="../img/baojing.png" style="width:30px;padding-left:10px;margin-top:-6px;"/>
                            </a-row>
                             <a-row>
                                <img src="../img/bianhao.png" style="width:16px">
                                <span style="height:16px;line-height:16px;margin-left:6px;color:#707070;">{{eq.deviceNo}}</span>
                            </a-row>
                        </template>
                        <template slot="content" v-else>
                            <a-row>
                                <img src="../img/bianhao.png" style="width:16px">
                                <span style="height:16px;line-height:16px;margin-left:6px;color:#707070;">{{eq.deviceNo}}</span>
                            </a-row>
                        </template>

                        <template v-if="eq.deviceType===defaultSettings.常量.设备类型_温湿度">
                            <div v-if="eq.lineState===defaultSettings.常量.否" :class='["icon","th-off"]' :style="{left: `${eq.pageLeft}%`,top: `${eq.pageTop}%`}" @click="showTh(eq)"></div>
                            <div v-else-if="eq.alarmState===defaultSettings.常量.是" :class='["icon","th-alarm"]' :style="{left: `${eq.pageLeft}%`,top: `${eq.pageTop}%`}" @click="showTh(eq)"></div>
                            <div v-else :class='["icon","th-normal"]' :style="{left: `${eq.pageLeft}%`,top: `${eq.pageTop}%`}" @click="showTh(eq)"></div>
                        </template>
                        <template v-else>
                            <div v-if="eq.lineState===defaultSettings.常量.否" :class='["icon","smoke-off"]' :style="{left: `${eq.pageLeft}%`,top: `${eq.pageTop}%`}" @click="showSmoked(eq)"></div>
                            <div v-else-if="eq.alarmState===defaultSettings.常量.是" :class='["icon","smoke-alarm"]' :style="{left: `${eq.pageLeft}%`,top: `${eq.pageTop}%`}" @click="showSmoked(eq)"></div>
                            <div v-else :class='["icon","smoke-normal"]' :style="{left: `${eq.pageLeft}%`,top: `${eq.pageTop}%`}" @click="showSmoked(eq)"></div>
                        </template>
                    </a-popover>
                </template>
            </div>
        </div>

        <!-- 固定在右侧中间的图标 -->
        <a-dropdown class="fixed-icon">
            <a-menu slot="overlay" @click="changeWork">
                <a-menu-item v-for="(item,i) in workList" :key="i">
                    <a href="javascript:;">{{item.name}}</a>
                </a-menu-item>
            </a-menu>
            <a class="ant-dropdown-link" @click="e => e.preventDefault()">更换车间<a-icon type="down" /></a>
        </a-dropdown>
        
        <!-- 缩放控制UI -->
        <div class="zoom-controls">
            <a-tooltip>
                <a-button type="primary" shape="circle" icon="plus" @click="zoomIn" class="zoom-btn" :disabled="scale >= maxScale"/>
            </a-tooltip>
            <a-tooltip>
                <a-button type="primary" shape="circle" icon="undo" @click="resetZoom" class="zoom-btn" :disabled="scale === 1 && position.x === 0 && position.y === 0"/>
            </a-tooltip>
            <a-tooltip>
                <a-button type="primary" shape="circle" icon="minus" @click="zoomOut" class="zoom-btn" :disabled="scale <= minScale"/>
            </a-tooltip>
            <div class="zoom-level">{{Math.round(scale * 100)}}%</div>
        </div>

        <ExtModal ref="ExtModal"></ExtModal>
    </div>
</template>

<script>
import { notification } from 'ant-design-vue';
import request from '@/utils/request';
import defaultSettings from '@/config/defaultSettings';
import screenfull from "screenfull";
import { ACCESS_TOKEN } from '@/store/mutation-types';
import ExtModal from '@/views/system/codeGenerator/ExtModal'
import {SysMixin} from '@/mixins/SysMixin'


export default {
    name: 'Workplace',
    components: {ExtModal},
    mixins:[SysMixin],

    data() {
        return {
            defaultSettings,
            isFullscreen: false,
            token: null,
            eqStateList: [],
            currentWorkEqList: [],
            timmer: null,
            currentWorkCode: '2',
            backgroundImageUrl: require('./img/work2.jpg'),
            workList: [
                { code: '2', name: '精整车间' ,url:'./img/work2.jpg'},
                { code: '1', name: '冷轧二车间',url:'./img/work1.jpg' }
            ],
            
            // 缩放相关数据
            scale: 1,
            minScale: 0.1,
            maxScale: 5,
            zoomStep: 0.2,
            position: { x: 0, y: 0 },
            dragging: false,
            dragStart: { x: 0, y: 0 },
            startPosition: { x: 0, y: 0 }
        }
    },
    computed: {
        zoomTransform() {
            return {
                transform: `scale(${this.scale}) translate(${this.position.x}px, ${this.position.y}px)`,
                transformOrigin: '0 0',
                transition: this.dragging ? 'none' : 'transform 0.15s ease'
            };
        },
        backgroundStyle() {
            return {
                backgroundImage: `url(${this.backgroundImageUrl})`,
                backgroundSize: 'contain',
                backgroundPosition: 'center center',
                backgroundRepeat: 'no-repeat',
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%'
            };
        }
    },
    created() {
        this.token = sessionStorage.getItem(ACCESS_TOKEN);
    },
    mounted() {
        this.$nextTick(() => {
            this.createEqIcon();
            if (screenfull.isEnabled) {
                screenfull.on('change', this.fullChange);
            }
        });
    },
    beforeDestroy() {
        if (screenfull.isEnabled) {
            screenfull.off('change', this.fullChange);
        }
        if (this.timmer) {
            clearTimeout(this.timmer);
        }
    },
    methods: {
        fullChange() {
            this.isFullscreen = screenfull.isFullscreen;
        },
        async query() {
            await request({
                url: '/ThEqStateController/viewList',
                method: 'post',
                data: {}
            }).then((res) => {
                if (res.success) {
                    this.eqStateList = res.result;
                } else {
                    notification.warning({ message: res.message });
                }
            });
        },
        async createEqIcon() {
            this.eqStateList = this.$store.state.eqState.eqStateList;
            if (this.eqStateList.length === 0) {
                await this.query();
            }
            this.currentWorkEqList = [];
            for (const eq of this.eqStateList) {
                if (eq['deviceRegion'] === this.currentWorkCode && eq["pageLeft"] && eq["pageTop"]) {
                    this.currentWorkEqList.push(eq);
                }
            }
            
            if (this.timmer) {
                clearTimeout(this.timmer);
            }
            this.timmer = setTimeout(() => { this.createEqIcon(); }, 10000);
        },
        changeWork(e) {
            this.currentWorkCode = this.workList[e.key].code;
            this.backgroundImageUrl = require(`${this.workList[e.key].url}`);
            this.createEqIcon();
            this.resetZoom(); // 切换车间时重置缩放
        },
        
        // 新增缩放方法
        handleWheel(e) {
            e.preventDefault();
            
            // 计算缩放中心
            const rect = this.$refs.container.getBoundingClientRect();
            const offsetX = e.clientX - rect.left;
            const offsetY = e.clientY - rect.top;
            
            // 判断滚轮方向
            const direction = e.deltaY < 0 ? 1 : -1;
            this.setScale(this.scale + direction * this.zoomStep, offsetX, offsetY);
        },
        
        setScale(newScale, mouseX, mouseY) {
            // 限制缩放范围
            newScale = Math.max(this.minScale, Math.min(newScale, this.maxScale));
            
            // 计算基于鼠标位置的偏移
            if (mouseX !== undefined && mouseY !== undefined) {
                const containerRect = this.$refs.container.getBoundingClientRect();
                
                // 计算鼠标在缩放容器中的位置比例
                const relativeX = mouseX / containerRect.width;
                const relativeY = mouseY / containerRect.height;
                
                // 计算新的偏移位置
                this.position.x = (1 - newScale / this.scale) * relativeX * containerRect.width + 
                                 this.position.x * (newScale / this.scale);
                this.position.y = (1 - newScale / this.scale) * relativeY * containerRect.height + 
                                 this.position.y * (newScale / this.scale);
            }
            
            this.scale = newScale;
        },
        
        zoomIn() {
            const container = this.$refs.container;
            const rect = container.getBoundingClientRect();
            this.setScale(this.scale + this.zoomStep, rect.width / 2, rect.height / 2);
        },
        
        zoomOut() {
            const container = this.$refs.container;
            const rect = container.getBoundingClientRect();
            this.setScale(this.scale - this.zoomStep, rect.width / 2, rect.height / 2);
        },
        
        resetZoom() {
            this.scale = 1;
            this.position = { x: 0, y: 0 };
        },
        
        // 拖拽相关方法
        startDrag(e) {
            if (this.scale <= 1) return;
            
            e.preventDefault();
            this.dragging = true;
            this.dragStart = { x: e.clientX, y: e.clientY };
            this.startPosition = { ...this.position };
            document.addEventListener('mousemove', this.onDrag);
            document.addEventListener('mouseup', this.endDrag);
            document.addEventListener('mouseleave', this.endDrag);
            this.$refs.container.style.cursor = 'grabbing';
        },
        
        onDrag(e) {
            if (!this.dragging) return;
            
            e.preventDefault();
            const dx = (e.clientX - this.dragStart.x) / this.scale;
            const dy = (e.clientY - this.dragStart.y) / this.scale;
            
            this.position.x = this.startPosition.x + dx;
            this.position.y = this.startPosition.y + dy;
        },
        
        endDrag() {
            this.dragging = false;
            document.removeEventListener('mousemove', this.onDrag);
            document.removeEventListener('mouseup', this.endDrag);
            document.removeEventListener('mouseleave', this.endDrag);
            this.$refs.container.style.cursor = 'grab';
        },
        
        // 全屏切换
        fullScreen() {
            if (!screenfull.isEnabled) return;
            screenfull.toggle(this.$refs.container);
        },
        showTh(item){
            this.sysPageOpen('1919964789616095233',item,'ExtModal',item.deviceName);
       },
       showSmoked(item){

        this.sysPageOpen('1939939955649474561',item,'ExtModal',item.deviceName);
       }
    }
}
</script>

<style lang="less" scoped>
.monitor-container {
    position: relative;
    width: 100%;
    height: 90vh;
    overflow: hidden;
    background-color: #E6E7E1;
    cursor: grab;
    user-select: none;
    margin-top: -20px;
    &:active {
        cursor: grabbing;
    }
}

.zoom-wrapper {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    will-change: transform;
}

/* 设备图标样式保持不变 */
.icon {
    position: absolute;
    width: 28px;
    height: 28px;
    background-size: cover;
    background-position: center;
    transform: translate(-50%, -50%);
    cursor: pointer;
    transition: transform 0.2s ease, filter 0.2s ease;
    z-index: 10;
    
    &:hover {
        transform: translate(-50%, -50%) scale(1.15);
        filter: drop-shadow(0 0 6px rgba(255, 255, 0, 0.8));
    }
}

/* 温湿度设备图标 */
.th-normal {
    background-image: url('./img/th-normal.png');
}
.th-alarm {
    background-image: url('./img/th-alarm.png');
    animation: alarmBlink 1.5s infinite;
}
.th-off {
    background-image: url('./img/th-off.png');
    opacity: 0.6;
}

/* 烟雾设备图标 */
.smoke-normal {
    background-image: url('./img/smoke-normal.png');
}
.smoke-alarm {
    background-image: url('./img/smoke-alarm.png');
    animation: alarmBlink 1.5s infinite;
}
.smoke-off {
    background-image: url('./img/smoke-off.png');
    opacity: 0.6;
}

@keyframes alarmBlink {
    0% { opacity: 1; }
    50% { opacity: 0.5; }
    100% { opacity: 1; }
}

/* 固定图标样式 */
.fixed-icon {
    position: fixed;
    right: 30px;
    top: 14%;
    transform: translateY(-50%);
    z-index: 999;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    animation: pulse 2s infinite;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:hover {
        transform: translateY(-50%) scale(1.1);
    }
}

@keyframes pulse {
    0% { box-shadow: 0 0 0 0 rgba(24, 144, 255, 0.4); }
    70% { box-shadow: 0 0 0 10px rgba(24, 144, 255, 0); }
    100% { box-shadow: 0 0 0 0 rgba(24, 144, 255, 0); }
}

/* 缩放控制UI */
.zoom-controls {
    position: fixed;
    right: 20px;
    bottom: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    z-index: 999;
    background: rgba(0, 0, 0, 0.6);
    border-radius: 24px;
    padding: 8px;
    backdrop-filter: blur(5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    
    .zoom-btn {
        margin: 8px 0;
        width: 40px;
        height: 40px;
        font-size: 16px;
        background: rgba(0, 0, 0, 0.4);
        border: 1px solid rgba(255, 255, 255, 0.2);
        
        &:not([disabled]):hover {
            transform: scale(1.1);
        }
        
        &[disabled] {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }
    }
    
    .zoom-level {
        color: white;
        font-weight: 500;
        font-size: 14px;
        margin-top: 4px;
        background: rgba(0, 0, 0, 0.4);
        border-radius: 12px;
        padding: 4px 12px;
        min-width: 50px;
        text-align: center;
    }
}
</style>